package com.yayohos.locationmanager;

import com.yayohos.locationmanager.constants.FailType;
import com.yayohos.locationmanager.helper.LogUtils;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;

import ohos.agp.components.Button;
import ohos.agp.components.Text;
import ohos.agp.utils.TextTool;

import ohos.event.commonevent.*;

import ohos.location.Location;

import ohos.rpc.RemoteException;

import static com.yayohos.locationmanager.SampleService.*;

/**
 * 在Service中定位
 */
public class SampleServiceAbility extends Ability implements SamplePresenter.SampleView {
    private SamplePresenter samplePresenter;
    private Text text_helloworld;
    private MyCommonEventSubscriber commonEventSubscriber;
    private Intent intent;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_sample_service);
        registerEvent();
        text_helloworld = (Text) findComponentById(ResourceTable.Id_text_helloworld);
        samplePresenter = new SamplePresenter(this);
        Button doLocation = (Button) findComponentById(ResourceTable.Id_do_location);
        doLocation.setClickedListener(component -> startService(SampleService.class.getName()));
    }

    private void startService(String pageName) {
        if (TextTool.isNullOrEmpty(pageName)) {
            return;
        }
        if (intent == null) {
            intent = new Intent();
        }
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withAbilityName(pageName)
                .withBundleName(getBundleName())
                .build();
        intent.setOperation(operation);
        startAbility(intent);
    }

    private void stopService() {
        stopAbility(intent);
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
        LogUtils.logI("onForeground" + true);
        registerEvent();
    }

    @Override
    protected void onBackground() {
        super.onBackground();
        LogUtils.logI("onForeground" + true);
        if (commonEventSubscriber == null) {
            return;
        }
        try {
            CommonEventManager.unsubscribeCommonEvent(commonEventSubscriber);
            LogUtils.logI("unsubscribeCommonEvent取消订阅");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        samplePresenter.destroy();
        stopService();
    }

    @Override
    public String getText() {
        return text_helloworld.getText();
    }

    @Override
    public void setText(String text) {
        text_helloworld.setText(text);
    }

    @Override
    public void updateProgress(String text) {
    }

    @Override
    public void dismissProgress() {
    }

    private void registerEvent() {
        MatchingSkills matchingSkills = new MatchingSkills();
        matchingSkills.addEvent(LOCATION_EVENT); // 自定义事件
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
        commonEventSubscriber = new MyCommonEventSubscriber(subscribeInfo);
        try {
            CommonEventManager.subscribeCommonEvent(commonEventSubscriber);
        } catch (RemoteException e) {
            LogUtils.logI(e.getMessage());
        }
    }

    /**
     * 广播
     */
    class MyCommonEventSubscriber extends CommonEventSubscriber {
        MyCommonEventSubscriber(CommonEventSubscribeInfo info) {
            super(info);
        }

        @Override
        public void onReceiveEvent(CommonEventData commonEventData) {
            Intent eventIntent = commonEventData.getIntent();
            if (eventIntent == null) {
                return;
            }
            int code = eventIntent.getIntParam("code", -1);
            LogUtils.logI(Thread.currentThread().getName() + "/" + code);
            switch (code) {
                case ACTION_LOCATION_CHANGED:
                    double lat = eventIntent.getDoubleParam("Lat", 0.0);
                    double lng = eventIntent.getDoubleParam("Lng", 0.0);
                    Location location = new Location(lat, lng);
                    samplePresenter.onLocationChanged(location);
                    break;
                case ACTION_LOCATION_FAILED:
                    samplePresenter.onLocationFailed(eventIntent.getIntParam(EXTRA_FAIL_TYPE, FailType.UNKNOWN));
                    break;
                case ACTION_PROCESS_CHANGED:
                    samplePresenter.onProcessTypeChanged(
                            eventIntent.getIntParam(EXTRA_PROCESS_TYPE, FailType.VIEW_NOT_REQUIRED_TYPE));
                    break;
                default:
                    break;
            }
        }
    }
}
